package com.magictower.primary.engine;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Xml;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.magictower.primary.bean.ContactInfo;

/**
 * @author kejunzhan
 * @since 2017/12/20
 */

public class ContactInfoParser {
    /**
     * 获取系统全部联系人的API方法
     *
     * @param context
     * @return
     */
    public static List<ContactInfo> findAll(Context context) {
        ContentResolver resolver = context.getContentResolver();
        //contacts表
        //联系人表的URI —— content://com.android.contacts/contact ，对应类静态常量为ContactsContract.Contacts.CONTENT_URI
        //联系人电话URI —— content://com.android.contacts/data/phones ，对应静态常量为ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        //联系人邮箱URI —— content://com.android.contacts/data/emails  ，对应静态常量为ContactsContract.CommonDataKinds.Email.CONTENT_URI
        //联系人地址URI —— content://com.android.contacts/data/postals  ，对应静态常量为ContactsContract.CommonDataKinds.StructuredPostall.CONTENT_URI
        //所有联系人的Uri —— content://contacts/people
        //某个联系人x的Ur —— content://contacts/people/x
        Uri rawContactsUri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");
        List<ContactInfo> infos = new ArrayList<>();
        ContactInfo info;
        Cursor rawContactsCursor = resolver.query(rawContactsUri,
                new String[]{"contact_id"}, null, null, null);
        while (rawContactsCursor.moveToNext()) {
            info = new ContactInfo();
            String id = rawContactsCursor.getString(0);
            info.setId(id);
            // 根据联系人的id，查询data表，把这个id的数据取出来
            // 系统api 查询data表的时候 不是真正的查询data表 而是查询的data表的视图
            Cursor dataCursor = resolver.query(dataUri, new String[]{"data1", "mimetype"},
                    "raw_contact_id=?", new String[]{id}, null);
            while (dataCursor.moveToNext()) {
                String data1 = dataCursor.getString(0);
                String mimeType = dataCursor.getString(1);
                if ("vnd.android.cursor.item/name".equals(mimeType)) {
                    info.setName(data1);
                } else if ("vnd.android.cursor.item/email_v2".equals(mimeType)) {
                    info.setEmail(data1);
                } else if ("vnd.android.cursor.item/phone_v2".equals(mimeType)) {
                    info.setPhone(data1);
                } else if ("vnd.android.cursor.item/im".equals(mimeType)) {
                    info.setQq(data1);
                }
            }
            infos.add(info);
            dataCursor.close();
        }
        rawContactsCursor.close();
        return infos;
    }

    /**
     * 回调接口
     */
    public interface BackCall {
        void before(int count);

        void onBackUp(int progress);
    }

    public static boolean backup(Context context, BackCall callback) {
        boolean res = false;
        //得到列表数据
        List<ContactInfo> list = findAll(context);
        int size = list.size();
        callback.before(size);
        ContactInfo info;
        try {
            FileOutputStream output = new FileOutputStream(
                    new File(Environment.getExternalStorageDirectory(), "contast.xml"));
            //得到序列解析器
            //在android中都pull解析器
            XmlSerializer serializer = Xml.newSerializer();
            //设置编码格式
            serializer.setOutput(output, "utf-8");
            //设置文件头
            serializer.startDocument("utf-8", true);
            //设置开始结点
            serializer.startTag(null, "contacts");
            //设置内容体
            for (int i = 0; i < size; i++) {
                info = list.get(i);
                System.out.println(info.toString());

                serializer.startTag(null, "name");
                serializer.text(info.getName());
                serializer.endTag(null, "name");

                String email = info.getEmail();
                if (!TextUtils.isEmpty(email)){
                    serializer.startTag(null, "email");
                    serializer.text(info.getEmail());
                    serializer.endTag(null, "email");
                }
                serializer.startTag(null, "phone");
                serializer.text(info.getPhone());
                serializer.endTag(null, "phone");

                String qq = info.getQq();
                if (!TextUtils.isEmpty(qq)){
                    serializer.startTag(null, "qq");
                    serializer.text(info.getQq());
                    serializer.endTag(null, "qq");
                }

                callback.onBackUp(i);
                SystemClock.sleep(300);
            }
            serializer.endTag(null, "contacts");
            res = true;
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}
